package hero_info

import (
	"go_server/game_server/api/service/bag"
	"go_server/game_server/api/service/item"
	"go_server/game_server/constants"
	"go_server/game_server/dataconfig/config_manager"
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/zinx/ziface"
	"go_server/zinx/zlog"
)

func (s *Hero_info_service) S2C_UniToExcFragments(conn ziface.IConnection, roleid int64, msg *pb.UniToExcFragmentsC2S) pb.ErrorCodeManager {
	msgS2C, code := onUniToExcFragments(roleid, msg.Herocfgid, msg.Fragments)
	defer func() {
		if msgS2C != nil {
			zlog.Debugf("ProtocolManager_UniToExcFragments %v", msgS2C)
			defer func() {
				conn.SendBuffPBMsg(uint32(pb.ProtocolManager_UniToExcFragments), msgS2C)
			}()
		}
	}()
	return code
}

func onUniToExcFragments(roleid int64, c2sherocftid int32, c2sfragments map[int32]int32) (*pb.UniToExcFragmentsS2C, pb.ErrorCodeManager) {
	if c2sfragments != nil {
		legitems := util.NewSet[int32]()

		if h1, ok1 := config_manager.GetStcTableHero_SheetHeroConfig(c2sherocftid); ok1 {
			legitems.Add(h1.Unlockitemid)                                                                                       //合法道具
			if crrencyfragments, ok := item.GetUpgradeHeroItems(constants.Item_Upgrade_HerocCrrencyFragments, h1.Quality); ok { //英雄通用碎片
				for id, _ := range crrencyfragments {
					legitems.Add(id)
				}
			}

			isAllOK := true

			for id, _ := range c2sfragments {
				isAllOK = isAllOK && legitems.Contains(id)
			}

			if isAllOK {
				subitems := make(map[int32]int32) //减少的道具
				additems := make(map[int32]int32) //增加的道具
				for id, count := range c2sfragments {
					if _, a1 := additems[h1.Unlockitemid]; a1 { //增加专属道具
						additems[h1.Unlockitemid] += count
					} else {
						additems[h1.Unlockitemid] = count
					}

					if _, s1 := subitems[id]; s1 { //减少通用道具
						subitems[id] += count
					} else {
						subitems[id] = count
					}
				}

				code, ok := bag.SubItemBatch(roleid, subitems)
				if !ok {
					return nil, code
				}
				bag.AddItemBatch(roleid, additems)

				msgS2C := &pb.UniToExcFragmentsS2C{
					Herocfgid: c2sherocftid,
					Fragments: c2sfragments,
				}
				return msgS2C, pb.ErrorCodeManager_SUCCESS
			} else {
				return nil, pb.ErrorCodeManager_HERO_INFO_NOTLEG_UNITOEXCFRAGMENTS
			}
		} else {
			return nil, pb.ErrorCodeManager_HERO_INFO_NOT_HEROCFGID
		}
	} else {
		return nil, pb.ErrorCodeManager_HERO_INFO_NOTLEG_UNITOEXCFRAGMENTS
	}
}
